package com.zzyl.service.impl;


import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.service.WechatService;
import com.zzyl.utils.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class WechatServiceImpl implements WechatService {

    // 登录
    private static final String  REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN";

    @Value("${zzyl.wechat.appId}")
    private String appId;

    @Value("${zzyl.wechat.appSecret}")
    private String secret;

    @Override
    public String getPhone(String code) {
//获取access_token
        String token = getToken();
        //拼接请求路径
        String phone_url_temp = PHONE_REQUEST_URL.replace("ACCESS_TOKEN",token);
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);

        String result = HttpUtil.post(phone_url_temp, JSONUtil.toJsonStr(param));
        log.info("获取手机号结果："+result);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.getInt("errcode") != 0) {
            //若code不正确，则获取不到phone，响应失败
            throw new BaseException(BasicEnum.GET_PHONE_ERROR);

        }
        return jsonObject.getJSONObject("phone_info").getStr("purePhoneNumber");
    }

    private String getToken() {
        String token_url_temp=TOKEN_URL.replace("APPID",appId).replace("APPSECRET",secret);
        String result = HttpUtil.get(token_url_temp);
        log.info("获取token结果："+result);
        //解析
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //如果code不正确，则失败
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new BaseException(BasicEnum.GET_TOKEN_ERROR);
        }
        return jsonObject.getStr("access_token");

    }

    @Override
    public String getOpenid(String code) {
        try {
            String openid_url_temp=REQUEST_URL.replace("APPID",appId).replace("SECRET",secret).replace("JSCODE",code);
            String result = HttpUtil.get(openid_url_temp);
            log.info("获取openid结果："+result);
            JSONObject jsonObject = JSONUtil.parseObj(result);
            Integer errcode = jsonObject.getInt("errcode");
            if (jsonObject.get("error_code")!= null){
                throw new BaseException(BasicEnum.GET_OPENID_ERROR);
            }
            return jsonObject.getStr("openid");
        } catch (Exception e) {
            throw new BaseException(BasicEnum.GET_OPENID_ERROR);
        }
    }


}
